// pages/service/index.js
import {
  getPackageList
} from "../../api/service";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    products: [], //商品列表
    filteredProducts: [], //筛选商品
    tagOptions: [{
        text: '全部',
        value: ''
      }
      // 其余选项将在onLoad时自动生成
    ],
    selectedTag: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getList()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      const route = "/" + this.route;
      const tabList = this.getTabBar().data.list;
      const current = tabList.find((i) => i.pagePath === route);
      if (current) {
        this.getTabBar().setData({
          value: current.value
        });
      }
    }
  },


  getList() {
    getPackageList()
      .then((res) => {
        console.log(res)
        const products = res.data;
        // 自动生成tag选项
        const tags = Array.from(new Set(products.map(p => p.tag)));
        const tagOptions = [{
            text: '全部',
            value: ''
          },
          ...tags.map(tag => ({
            text: tag,
            value: tag
          }))
        ];
        this.setData({
          products,
          filteredProducts: products,
          tagOptions
        });
      })
      .catch((res) => {
        console.log(res)
        wx.showToast({
          title: '商品加载失败，请稍后重试',
        })
      });
  },

  onTagChange(e) {
    const selectedTag = e.detail;
    const filteredProducts = selectedTag ?
      this.data.products.filter(p => p.tag === selectedTag) :
      this.data.products;
    this.setData({
      selectedTag,
      filteredProducts
    });
  },
  //点击商品卡片
  handleClick(e) {
    const index = e.currentTarget.dataset.id;
    const item = this.data.products[index];
    if (!item) return;
    // 跳转到商品详情页，并携带商品id参数
    wx.navigateTo({
      url: `/pages/productDetails/index?id=${item.id}`,
    });
  },

  onPullDownRefresh() {
    wx.showToast({
      title: '刷新中...',
      icon: 'loading',
    })
    this.getList(); // 刷新数据
    wx.stopPullDownRefresh();
  },
})